import json
import logging

from django.http import JsonResponse
from django.shortcuts import render
from wxcloudrun.models import duty
from wxcloudrun.models import tmpobj

logger = logging.getLogger('log')


def clear():  # 删除原有的数据
    data = duty.objects.all()
    data.delete()


def savelog(str1):
    obj = tmpobj()
    obj.data = str(str1)
    obj.save()


def savedata(item):
    obj = duty()
    obj.area_id = item.get('area_id')
    obj.user_id = item.get('user_id')
    obj.save()


def adddata(request, _):
    '''
    增加小区数据
    '''
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    print(body)
    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    if request.method == 'POST' or request.method == 'post':
        if (body['action'] == 'clear'):
            clear()  # 删除原来的数据

        if (body['action'] == 'saveall'):
            dataobj = body['data']
            for item in dataobj:
                savedata(item)
            body = {'code': 0, 'errorMsg': ''}
        rsp = JsonResponse(body, json_dumps_params={'ensure_ascii': False})
    else:
        rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                           json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))

    return rsp
